<?php
/*
 * Created on Mar 27, 2009
 * author: ANH
 * fileName: IndexController.php
 */
 
 class File_BlockController extends Clu_Controller_Action_Mini
{
	/*
	public function init()
	{
		$this->m = new user_Model_User();
	}
	*/
	
	/**
	 *@abstract This action serves as a service for the other modules
	 *  for example, when posting a place, user wants to add a list of files to the place # 1256
	 *  then he can call /en/file/index/upload?c=place&t=image&id=1256&uid=1
	 *  
	 *  This action should present the user with 1 div: 
	 * 		- 1 to upload the file.
	 * 		- 1 div->iframe to display the files already uploaded with this place #id already (starting with 1256)
	 * 		 /public/ustore/$userId/images/place/1256_pic1.jpg
	 * 		 /public/ustore/$userId/images/place/1256_pic2-sanitized-name.jpg
	 * 		Each image is also attached with a "Delete" link to delete the image. then only the iframe is reloaded
	 * 
	 * @see generate_image_copies for how the images are stored
	 * @note: At of 04 May 2009, this targets at uploading images for place module, or user... only
	 *  but it sure can be extended to serve other files
	 * 
	 * 
	 * 
	 */ 
	public function uploadAction()
	{
		//get module name & id here
		$contentType = $this->miniRequest['c'];
		$id = $this->miniRequest['id'];
		$fileType = $this->miniRequest['t']; 
		$uid = $this->miniRequest['uid'];
		if (!$contentType || !$id || !$fileType)
			die("contentType or id or fileType is not specified. Die!!");
			
		//TODO: check user authorization, if the user is actually responsible for this contentId
		//other wise a user can upload his own shit to his /place/1235_pic.jpg for example even
		//if he did not create place#1235
		//This has to be checked from calling module, not here
		//or user is allowed to edit content
			
		//allowed, now continue
    	$sess = new Zend_Session_Namespace(CLU_NS);
    	$form = new Form_Upload();
    	$form->cluBuild($contentType, $id, $uid, $fileType);
    	$this->view->id = $id;
    	$this->view->uid = $uid;
    	$this->view->t = $fileType;
    	$this->view->c = $contentType;
    	$this->view->form = $form;
    	if($this->_request->isPost())
		{
			$formData = $this->_request->getPost();
			if ($form->isValid($formData) && $fileType == 'image') 
					$this->postImage($contentType, $id, $uid, true);
		}
		
    	//$iframe = $this->view->render($sess->viewLang . "/account/update-avatar-iframe.phtml");
//    	$this->renderToHolder("block/upload.phtml");
    	$txt = $this->view->render($sess->viewLang."/index/upload.phtml");
		echo $txt;
	}

	public function imageListAction()
	{
		$contentType = $this->miniRequest['c'];
		$id = $this->miniRequest['id'];
		$fileType = $this->miniRequest['t']; /*image, flash, doc ..*/ 
		$userId = $this->miniRequest['uid'];
		
		if (!$contentType || !$id || !$fileType)
			die("contentType or id or fileType is not specified. Die!!");
		//find the directory
		
		$dir = APP_PATH."/public/ufiles/$userId/images/original/$contentType/";
		if(file_exists($dir))
		{
		    $files = scandir($dir);
		    $displayFiles = array();
		    foreach ($files as $f)
		    {
		    	if (strpos ($f, $id) === 0)
		    	{
			    	$ctime = filectime($dir . $f); 
		    		$displayFiles[$f] = $ctime;
		    	}
		    }
		}
		if (isset($displayFiles) && count ($displayFiles) > 0)
		{
		    asort($displayFiles);
		    //die_a($displayFiles);
    	    $this->view->displayFiles = $displayFiles;
    	    $this->view->base = "/public/ufiles/$userId/images/%s/$contentType/";
    	    if ($this->miniRequest['regionId'] == 6)//5)
    	    {
    	    	die('nva');
    	    	$this->view->itemWidth = 76;
    	    	$this->view->mainImageSize = 'medium'; //260px
    	    	$this->view->thumbSize = 'xsmall';
    	    	$region = $this->miniRequest['regionId'];
    	    	$weight = $this->miniRequest['boxWeight'];
    	    }
    	    if ($this->miniRequest['regionId'] == 4)
    	    {
    	    	$this->view->itemWidth = 106;
    	    	$this->view->mainImageSize = 'large'; //350px
    	    	$this->view->thumbSize = 'small';
    	    	$region = $this->miniRequest['regionId'];
    	    	$weight = $this->miniRequest['boxWeight'];
    	    }
    	    
    	    $this->view->galleryId = $this->miniRequest['galleryId'];
    	    $this->renderToHolder("block/thumbnail-list.phtml", false, null, $region, $weight);
		}
	}

	public function deleteFileAction()
	{
	
	}
	
	public function postImage($contentType, $contentId, $userId, $createWM)
	{
		//require_once APP_PATH."/library/common.php";
		$watermarkDir = APP_PATH."/public/watermark/";

		//see generate_image_copies() @ /library/common.php
		$ustoreDir = APP_PATH."/public/ustore/$userId/images/original/$contentType/";
		if (!file_exists($ustoreDir))
			mkdir($ustoreDir, 0777  , true);

		$ufilesDir = APP_PATH."/public/ufiles/$userId/images/original/$contentType/" ; //just for avatar
		if (!file_exists($ufilesDir))
			mkdir($ufilesDir, 0777  , true);
		
		$adapter= new Zend_File_Transfer_Adapter_Http();

		//normal content type like place#2135 is different from uploading avatar
		if ($contentType == 'avatar')
    	{
    		$originalFilename = "avatar.jpg";
    		$configSizes = array("xxsmall", "xsmall", "small", "medium");
    		$configSizesInPixel = array("30", "75", "100", "260");
    		//delete current images first
    		foreach ($configSizes as $size)
    		{
    			unlink(APP_PATH."/public/ufiles/$userId/images/$size/avatar/avatar.jpg");
    		}
    	}
		else //uploading content is a little different from avatar as there is only 1 avatar per user
		{
    		$extension_path = pathinfo($_FILES['file_upload']['name']);
    		$fileName = $extension_path['filename'];
    		$extension =  $extension_path['extension'];
    		
    		if (empty($extension))
    		{		
    			$mimeType = $_FILES['file_upload']['type'];
    			$extension = explode('/', $mimeType);
    		}
    
    		$saneFileName = SanitizeFileName($fileName);
    		$i = 1;
    		while(file_exists($ustoreDir. $contentId . '_' . $saneFileName . "." . $extension))
    		{
    			$saneFileName = $saneFileName . "_" .$i;
    			$i++;
    		}
    		$originalFilename =  $contentId . '_' . $saneFileName . "." . $extension;
    		//$originalFilename = $contentId . '_' . $saneFileName . "." . $extension
		}
		//now that we have the file name. Let's get it    		    	          	
		try 
		{
			$adapter->addFilter('Rename', array('target' => $ustoreDir. $originalFilename, 'overwrite' => true));
			$adapter->receive();
		}
		catch (Zend_File_Transfer_Exception $e) 
		{
		     $e->getMessage();
		}
		chmod($ustoreDir. $originalFilename, 0666);
		//die_a(array("ustore", $ustoreDir, $saneFileName, $watermarkDir, null, null, $userId, true) );
		if ($contentType == 'avatar')
    		generate_image_copies ("ustore", $ustoreDir, $originalFilename, $watermarkDir, $configSizes, $configSizesInPixel, $userId, false);    	
		else 
		{
			generate_image_copies ("ustore", $ustoreDir,$originalFilename, $watermarkDir, null, null, $userId, true); //with wm
			//die_a(array("ustore", $ustoreDir,$originalFilename, $watermarkDir, null, null, $userId, true));
		}                
	}
		
	
}
?>
